import os
from app.models.new_upload_model import upload_file,NewSample
from app.controllers.upload_controller import apply_file_upload_lease
from app.models.upload_model import Sample, calculate_file_md5
from config import ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET, WORKSPACE_ID

def add_file(
    LeaseId:str,
    Parser:str,
    CategoryId:str,
    file_name:str
):
    try:
        if not ALIYUN_ACCESS_KEY_ID or not ALIYUN_ACCESS_KEY_SECRET or not WORKSPACE_ID:
            return {"error": "请设置 ALIYUN_ACCESS_KEY_ID 和 ALIYUN_ACCESS_KEY_SECRET 和 WORKSPACE_ID 环境变量"}

        result = NewSample.call_api(
            ALIYUN_ACCESS_KEY_ID,
            ALIYUN_ACCESS_KEY_SECRET,
            WORKSPACE_ID,
            LeaseId,
            Parser,
            CategoryId,
            file_name,
        )
        return result
    except FileNotFoundError:
        return {"error": f"文件 {file_name} 未找到"}
    except Exception as e:
        return {"error": str(e)}

async def new_upload_file(file, category_id):
    # 这里简单示例，使用固定的 workspace_id，可根据需求修改
    workspace_id = WORKSPACE_ID
    file_name = file.filename

    try:
        # 读取文件内容获取文件大小
        content = await file.read()
        file.file.seek(0)  # 将文件指针重置到文件开头
        size_in_bytes = len(content)
        md5 = calculate_file_md5(file_name)
        print(file_name)
        lease_result = await apply_file_upload_lease(category_id, workspace_id,file_name, size_in_bytes,md5)
        print(lease_result)
        pre_signed_url = lease_result.get('PreSignedUrl')
        if not pre_signed_url:
            return {"error": "未能获取到预签名 URL"}
        result = await upload_file(pre_signed_url, file)
        return result
    except FileNotFoundError:
        return {"error": f"文件 {file_name} 不存在"}
    except Exception as e:
        return {"error": f"上传文件时发生错误: {str(e)}"}